package com.shengruan.admin.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.shengruan.admin.vo.Shipping;
import com.shengruan.framework.jdbc.BaseJdbc;
import com.shengruan.framework.jdbc.BeanHandler;
import com.shengruan.framework.jdbc.BeanListHandler;

public class ShippingJdbc extends BaseJdbc {

    public static final String SHIPPING_INSERT = "insert into shipping (name, creationTime, status, amount)values(?,?,?,?)";

    public static final String SHIPPING_DELETEBYID = "delete from shipping  where id = ?";

    public static final String SHIPPING_UPDATE = "UPDATE shipping SET NAME = ? , creationTime = ? , STATUS = ? , amount =? WHERE id = ?";

    public void save(Shipping shipping) {
        Connection conn = this.getConnection();
        Object[] pram = {shipping.getName(), shipping.getCreationTime(), shipping.getStatus(), shipping.getAmount()};
        try {
            this.execute(conn, SHIPPING_INSERT, pram);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.close(conn);
        }
    }

    public void update(Shipping shipping) {
        Connection conn = this.getConnection();
        Object[] pram = {shipping.getName(), shipping.getCreationTime(), shipping.getStatus(), shipping.getAmount(), shipping.getId()};
        try {
			this.execute(conn, SHIPPING_UPDATE, pram);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.close(conn);
		}
    }

    public List<Shipping> findAll() {
        List<Shipping> shippingList = new ArrayList<Shipping>();
        Connection conn = this.getConnection();
        String sql = "select * from shipping order by creationTime desc";
        try {
            shippingList = this.query(conn, sql, new BeanListHandler<Shipping>(Shipping.class));
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.close(conn);
        }
        return shippingList;
    }


    public Shipping getById(int id) {
        Connection conn = this.getConnection();
        StringBuilder sql = new StringBuilder("SELECT * FROM shipping s where s.id = ?");
		Shipping shipping = null;
		try {
			shipping = this.query(conn, sql.toString(), new BeanHandler<Shipping>(Shipping.class),id);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.close(conn);
		}
		return shipping;
	}

    public void deleteById(int id)throws SQLException{
		Connection conn = this.getConnection();
		try {
			this.execute(conn, SHIPPING_DELETEBYID,new Object[]{id});
		} catch (SQLException e) {
			throw e;
		} finally {
			close(conn);
		}
	}
}
